package com.example.demo.service.impl;

import com.example.demo.service.UserService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Created by Administrator on 2017/5/16.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void create(String name, String age) {
        jdbcTemplate.update("insert into transaction_user(NAME, AGE) values(?, ?)", name, age);
    }

    @Override
    public void deleteByName(String name) {
        jdbcTemplate.update("delete from transaction_user where NAME = ?", name);
    }

    @Override
    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from transaction_user", Integer.class);
    }

    @Override
    public void deleteAllUsers() {
        jdbcTemplate.update("delete from transaction_user");
    }

    @Override
    @Transactional
    public void transaction_test(String name, String age) {
        jdbcTemplate.update("insert into transaction_user(NAME, AGE) values(?, ?)", name, age);
        jdbcTemplate.update("delete from transaction_user where NAME = ?", "张三");
        throw new RuntimeException("手动抛异常,触发事务回滚");
    }

    @Override
    @Transactional
    public int transaction_user(Map<String,String> paramMap) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
                .create();
        int rv = 0;
        jdbcTemplate.update("insert into transaction_user(NAME, AGE) values(?, ?)", paramMap.get("name"), paramMap.get("age"));
        rv = jdbcTemplate.update("INSERT INTO transaction_eventPublish(status,payload,eventType) VALUES (?,?,?)","new",gson.toJson(paramMap),"insert");
        //throw new RuntimeException("手动抛异常");
        return rv;
    }
}
